﻿namespace AutoTest.Framework.Ioc
{
    /// <summary>
    /// 别名服务
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <param name="registrations"></param>
    public class NamedServiceProvider(IServiceProvider serviceProvider, IDictionary<string, Type> registrations) : INamedServiceProvider
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly IServiceProvider _serviceProvider = serviceProvider;
        /// <summary>
        /// 字典
        /// </summary>
        private readonly IDictionary<string, Type> _registrations = registrations;

        /// <summary>
        /// 根据别名获取服务
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public TService? GetService<TService>(string serviceName)
        {
            string mapServiceName = $"{typeof(TService).FullName}_{serviceName}";
            if (!_registrations.TryGetValue(mapServiceName, out var implementationType))
                throw new ArgumentException($"Service \"{serviceName}\" is not registered in container");
            var typeList = _serviceProvider.GetService(typeof(IEnumerable<TService>)) as IEnumerable<TService> ?? new List<TService>();
            return typeList.FirstOrDefault(t =>t?.GetType().FullName == implementationType.FullName);
            //return (TService)_serviceProvider.GetService(implementationType)!;
        }
    }
}
